// 摄影参数计算器的JavaScript代码

// Helper function to parse shutter speed values (fractions, numbers, 'B')
function parseShutterSpeed(value) {
    if (value === 'B') {
        // Represent Bulb mode as Infinity or a very large number for calculations if needed,
        // or handle it as a special case where direct EV calculation isn't applicable.
        // For now, returning NaN to indicate it's not a standard numeric value for EV formula.
        return NaN; 
    }
    if (value.includes('/')) {
        const parts = value.split('/');
        return parseFloat(parts[0]) / parseFloat(parts[1]);
    }
    return parseFloat(value);
}

document.addEventListener('DOMContentLoaded', () => {
    // 初始化Feather图标
    feather.replace();
    
    // 曝光值计算
    document.getElementById('calculate-ev').addEventListener('click', () => {
        const aperture = parseFloat(document.getElementById('aperture').value);
        const shutterSpeedValue = document.getElementById('shutter-speed').value;
        const shutterSpeed = parseShutterSpeed(shutterSpeedValue);
        const iso = parseInt(document.getElementById('iso').value);
        
        if (isNaN(shutterSpeed)) {
            document.getElementById('ev-value').textContent = 'N/A (B门)';
            return;
        }
        
        // 曝光值计算公式: EV = log2(aperture²/shutterSpeed) - log2(iso/100)
        const ev = Math.log2((aperture * aperture) / shutterSpeed) - Math.log2(iso / 100);
        
        document.getElementById('ev-value').textContent = ev.toFixed(1);
    });
    
    // 景深计算
    document.getElementById('calculate-dof').addEventListener('click', () => {
        const focalLength = parseFloat(document.getElementById('focal-length').value);
        const aperture = parseFloat(document.getElementById('dof-aperture').value);
        const subjectDistance = parseFloat(document.getElementById('subject-distance').value) * 1000; // 转换为毫米
        
        // 假设的焦点模糊圈直径 (mm)
        const circleOfConfusion = 0.029;
        
        // 计算超焦距
        const hyperFocal = (focalLength * focalLength) / (aperture * circleOfConfusion) + focalLength;
        
        // 计算近景深
        const nearDof = (subjectDistance * (hyperFocal - focalLength)) / (hyperFocal + subjectDistance - 2 * focalLength);
        
        // 计算远景深
        const farDof = (subjectDistance * (hyperFocal - focalLength)) / (hyperFocal - subjectDistance);
        
        // 计算总景深
        const totalDof = farDof - nearDof;
        
        // 显示结果 (转换回米)
        document.getElementById('near-dof').textContent = (nearDof / 1000).toFixed(2);
        document.getElementById('far-dof').textContent = farDof > 1000000 ? '无限' : (farDof / 1000).toFixed(2);
        document.getElementById('total-dof').textContent = farDof > 1000000 ? '无限' : (totalDof / 1000).toFixed(2);
    });
    
    // 参数调节计算器
    // 根据选择的参数隐藏/显示相应的输入组
    const paramToCalculate = document.getElementById('param-to-calculate');
    const apertureInputGroup = document.getElementById('aperture-input-group');
    const shutterInputGroup = document.getElementById('shutter-input-group');
    const isoInputGroup = document.getElementById('iso-input-group');
    const ndInputGroup = document.getElementById('nd-input-group');
    
    function updateInputVisibility() {
        const selectedParam = paramToCalculate.value;
        
        apertureInputGroup.style.display = selectedParam === 'aperture' ? 'none' : 'block';
        shutterInputGroup.style.display = selectedParam === 'shutter' ? 'none' : 'block';
        isoInputGroup.style.display = selectedParam === 'iso' ? 'none' : 'block';
        ndInputGroup.style.display = selectedParam === 'nd' ? 'none' : 'block';
    }
    
    // 初始化时更新一次
    updateInputVisibility();
    
    // 当选择变化时更新
    paramToCalculate.addEventListener('change', updateInputVisibility);
    
    // 计算参数
    document.getElementById('calculate-param').addEventListener('click', () => {
        const targetEV = parseFloat(document.getElementById('target-ev').value);
        const selectedParam = paramToCalculate.value;
        
        // 获取已知参数值
        let aperture = selectedParam === 'aperture' ? null : parseFloat(document.getElementById('param-aperture').value);
        let shutterSpeedValue = selectedParam === 'shutter' ? null : document.getElementById('param-shutter').value;
        let shutterSpeed = shutterSpeedValue ? parseShutterSpeed(shutterSpeedValue) : null;
        let iso = selectedParam === 'iso' ? null : parseInt(document.getElementById('param-iso').value);
        let nd = selectedParam === 'nd' ? null : parseInt(document.getElementById('param-nd').value);

        // Handle cases where a known parameter is 'B' - calculation might be invalid
        if (selectedParam !== 'shutter' && isNaN(shutterSpeed)) {
             document.getElementById('param-value').textContent = '无法计算 (快门为B门)';
             return;
        }
        
        // 如果ND为0，则视为无ND滤镜
        if (nd === 0) {
            nd = 1; // ND0 = 无滤镜，不影响曝光
        }
        
        let result = '';
        
        // 根据曝光值公式计算未知参数
        // EV = log2(aperture²/(shutterSpeed * nd)) - log2(iso/100)
        // 变换公式计算不同参数
        
        switch (selectedParam) {
            case 'aperture':
                // 计算光圈值
                // aperture² = shutterSpeed * nd * 2^(EV + log2(iso/100))
                const apertureSquared = shutterSpeed * nd * Math.pow(2, targetEV + Math.log2(iso / 100));
                const calculatedAperture = Math.sqrt(apertureSquared);
                
                // 找到最接近的标准光圈值
                const standardApertures = [1.2, 1.4, 2, 2.8, 4, 5.6, 8, 11, 16, 22];
                let closestAperture = standardApertures.reduce((prev, curr) => 
                    Math.abs(curr - calculatedAperture) < Math.abs(prev - calculatedAperture) ? curr : prev
                );
                
                result = `光圈值: f/${closestAperture.toFixed(1)} (计算值: f/${calculatedAperture.toFixed(2)})`;
                break;
                
            case 'shutter':
                // 计算快门速度
                // shutterSpeed = aperture² / (nd * 2^(EV + log2(iso/100)))
                const calculatedShutterSpeed = (aperture * aperture) / (nd * Math.pow(2, targetEV + Math.log2(iso / 100)));
                
                // 找到最接近的标准快门速度 (Numeric values only for comparison)
                const standardShutterSpeeds = [
                    1/8000, 1/4000, 1/2000, 1/1000, 1/500, 1/250, 1/125, 1/60, 1/30, 1/15, 1/8, 1/4, 1/2, 
                    1, 2, 4, 8, 15, 30
                ];
                // Filter out non-numeric values before reducing, although the array is now numeric
                let closestShutter = standardShutterSpeeds.filter(speed => typeof speed === 'number').reduce((prev, curr) => 
                    Math.abs(curr - calculatedShutterSpeed) < Math.abs(prev - calculatedShutterSpeed) ? curr : prev
                );
                
                // 格式化显示
                let formattedShutter = closestShutter < 1 ? 
                    `1/${Math.round(1/closestShutter)}` : 
                    `${closestShutter}`;
                    
                result = `快门速度: ${formattedShutter}秒 (计算值: ${calculatedShutterSpeed.toFixed(4)}秒)`;
                break;
                
            case 'iso':
                // 计算ISO
                // iso = 100 * 2^(log2(aperture²/(shutterSpeed * nd)) - EV)
                const calculatedISO = 100 * Math.pow(2, Math.log2((aperture * aperture) / (shutterSpeed * nd)) - targetEV);
                
                // 找到最接近的标准ISO值
                const standardISOs = [50, 100, 200, 400, 800, 1600, 3200, 6400, 12800, 25600, 32000, 51200, 102400];
                let closestISO = standardISOs.reduce((prev, curr) => 
                    Math.abs(curr - calculatedISO) < Math.abs(prev - calculatedISO) ? curr : prev
                );
                
                result = `ISO感光度: ${closestISO} (计算值: ${Math.round(calculatedISO)})`;
                break;
                
            case 'nd':
                // 计算ND值
                // 首先计算当前参数下的实际EV值
                const actualEV = Math.log2((aperture * aperture) / shutterSpeed) - Math.log2(iso / 100);
                
                // 比较实际EV和目标EV
                if (actualEV < targetEV) {
                    // 实际EV小于目标EV，表示过曝需要减少曝光，计算所需ND档数
                    const stopsNeeded = targetEV - actualEV;
                    const calculatedND = Math.pow(2, stopsNeeded);
                    
                    const standardNDs = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1000, 2000];
                    let closestND = standardNDs.reduce((prev, curr) => 
                        Math.abs(curr - calculatedND) < Math.abs(prev - calculatedND) ? curr : prev
                    );
                    
                    const actualStops = Math.log2(closestND);
                    result = `ND滤镜: ND${closestND} (减少${actualStops.toFixed(1)}档) (计算值: ${calculatedND.toFixed(2)})`;
                } else {
                    // 实际EV大于等于目标EV，表示欠曝或正常，不需要ND滤镜
                    const overexposureStops = actualEV - targetEV;
                    if (overexposureStops > 0) {
                        result = `不需要ND滤镜，当前参数已欠曝${overexposureStops.toFixed(1)}档，需要增加曝光`;
                    } else {
                        result = `不需要ND滤镜，当前参数与目标曝光值匹配`;
                    }
                }
                break;
        }
        
        document.getElementById('param-value').textContent = result;
    });
});